import { ref, toRefs, reactive, computed, onBeforeMount } from 'vue'
import { indexApi } from '@/api'
export default () => {   
    const pageSize = 10
    const currentPage = ref(1)
    const listData = reactive([])
    const totalPage = computed(() => Math.ceil(listData.length / pageSize))
    const params = reactive({
        listRef: null,
        pageList: computed(() => {
            return listData.slice(0, currentPage.value * pageSize)
        })
    })

    // 获取推荐视频
    const getList = async () => {
        try {
            const { data } = await indexApi.getRecommand()
            if (!data) {
                return
            }            
            const { list } = data
            if (!Array.isArray(list)) {
                completeLoad()
                return
            }
            listData.splice(0, listData.length)
            listData.push(...list)       
        } catch (error) {
            console.log(error)
        } finally {
            stopLoad()
            stopRefresh()
        }        
    }

    const stopLoad = () => {
        params.listRef?.stopLoad()
    }
    const stopRefresh = () => {
        params.listRef?.stopRefresh()
    }
    const completeLoad = () => {
        params.listRef?.completeLoad()
    }

    const onLoad = () => {      
        if (currentPage.value < totalPage.value) {
            currentPage.value += 1
        } else if (currentPage.value === totalPage.value) {
            completeLoad()
        }
        stopLoad()
    }

    const onRefresh = () => {
        currentPage.value = 1
        getList()
    }

    onBeforeMount(() => {
        getList()
    })

    return {
        ...toRefs(params),
        onLoad,
        onRefresh
    }
}